/**
 * 
 */
package com.swn.common.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @功能描述: 结果集与对象动态映射工具类
 * 
 * @创建人： 李刚
 * @创建时间：2016-4-28 下午4:23:00
 * 
 */
public class DynamicResultSetMapping {
	
	/**功能说明:<此处是项目功能>
	 *	
	 * @author  : Leon
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 * @date    : 2016-4-28 下午4:31:24
	 * @modifier: 
	 * @mod_Date: 
	 */
	@SuppressWarnings("unchecked")
	public <T> T readValue(Map<String, Object> map, Class<?> clazz) throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		if (map.isEmpty()) {
			map = new HashMap<String, Object>();
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.putAll(map);
		jsonObject = this.transObject(jsonObject);
		
		mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
		return(T) mapper.readValue(jsonObject.toString(),clazz);
	}

	public JSONObject transObject(JSONObject jsonObject) {
		JSONObject json = new JSONObject();
		Iterator<?> it = jsonObject.keys();
		while (it.hasNext()) {
			String key = (String) it.next();
			Object o = jsonObject.get(key);
			if (o.getClass().toString().endsWith("String")) {
				json.accumulate(key.toLowerCase(), o);
			} else if (o.getClass().toString().endsWith("JSONObject")) {
				json.accumulate(key.toLowerCase(),
						this.transObject((JSONObject) o));
			} else if (o.getClass().toString().endsWith("JSONArray")) {
				json.accumulate(key.toLowerCase(),
						this.transArray(jsonObject.getJSONArray(key)));
			}
		}
		return json;
	}

	public JSONArray transArray(JSONArray jsonArray) {
		JSONArray array = new JSONArray();
		for (int i = 0; i < jsonArray.size(); i++) {
			Object o = jsonArray.getJSONObject(i);
			if (o.getClass().toString().endsWith("JSONObject")) {
				array.add(transObject((JSONObject) o));
			} else if (o.getClass().toString().endsWith("JSONArray")) {
				array.add(transArray((JSONArray) o));
			}
		}
		return array;
	}
}
